<?php
namespace App\Repositories;
use App\Scopes\StatusScope;

trait BaseRepository {

	abstract protected function searchColumn($query, $where);

	public function page($page = 1, $page_size = 10, $where = false, $sort = 'asc', $sortColumn = 'id') {
		return $this->model->when($where, function ($query) use ($where) {
			return $this->searchColumn($query, json_decode($where, true));
		})->offset(($page - 1) * $page_size)->limit($page_size)->orderBy($sortColumn, $sort)->take($page_size)->get();
	}

	public function countRaws($where = false) {
		return $this->model->when($where, function ($query) use ($where) {
			return $this->searchColumn($query, json_decode($where, true));
		})->count();
	}

	public function withOutStatus() {
		$this->model = $this->model->withoutGlobalScope(StatusScope::class);
		return $this;
	}

	public function getById($id) {
		return $this->model->findOrFail($id);
	}

	public function update($id, $input) {
		$this->model = $this->getById($id);
		return $this->save($this->model, $input);
	}

	public function store($input) {
		return $this->save($this->model, $input);
	}

	public function destroy($id) {
		if (is_array($id)) {
			return $this->model->whereIn('id', $id)->delete();
		}
		return $this->getById($id)->delete();
	}

	public function save($model, $input) {
		$model->fill($input);
		$model->save();
		return $model;
	}

	public function __call($method, $arg) {
		return $this->model->{$method}(...$arg);
	}
}